package com.entities.projectitem.detail;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.core.protocols.ICustomDatasourceDelegate;
import com.core.protocols.IDescriptionViewDelegate;
import com.core.protocols.IDetailTableViewDelegate;
import com.core.protocols.IServiceLayerDelegate;
import com.core.protocols.ITabSheetDatasource;
import com.core.servicelayer.HibernateServiceLayer;
import com.core.ui.controller.base.HibernateDetailController;
import com.core.ui.customcell.TabSheetItemCell;
import com.core.utils.KeyValueDictionary;
import com.core.utils.LocalizableString;
import com.entities.projectitem.servicelayer.ProjectListLayer;
import com.entities.user.servicelayer.UserListLayer;
import com.model.KeyValue;
import com.model.project.ProjectItem;
import com.model.user.User;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class ProjectDetailController
        extends HibernateDetailController
        implements IDetailTableViewDelegate, IDescriptionViewDelegate, ITabSheetDatasource, IServiceLayerDelegate {


	private ProjectListLayer   projectListLayer                 = null;

	private UserListLayer      taskReporterServiceLayer         = null;
	private UserListLayer      taskAssigneeServiceLayer         = null;

	private final int          taskAssigneeFetchRequestUserInfo = 205;
	private final int          taskReporterFetchRequestUserInfo = 206;

	private KeyValueDictionary projectAssigneeDictionary        = null;
	private KeyValueDictionary projectReporterDictionary        = null;



	public ProjectDetailController() {

		super();
		projectListLayer = new ProjectListLayer();
	}



	@Override
	public <T> void responseResponseItemsList ( final List <T> items,
	                                            final Object request,
	                                            final Exception exception ) {

		if ( request == null ) {
			return;
		}

		HibernateServiceLayer serviceLayer = (HibernateServiceLayer) request;
		Integer userInfo = (Integer) serviceLayer.getUserInfo();
		if ( userInfo == null ) {
			return;
		}


		switch ( userInfo ) {
			case taskAssigneeFetchRequestUserInfo: {
				this.projectAssigneeResponseItems(items);
				break;
			}
			case taskReporterFetchRequestUserInfo: {
				this.projectReporterResponseItems(items);
				break;
			}
			default: {
				break;
			}
		}
	}



	private String projectCreatedCell ( ProjectItem projectItem,
	                                    boolean readOnly ) {

		String result = null;
		String propertyValue = null;
		Date createDate = null;
		if ( projectItem != null ) {
			createDate = projectItem.getCreateDate();
		}

		if ( createDate == null ) {
			createDate = new Date();
		}

		try {
			final DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
			final Calendar cal = dateFormat.getCalendar();
			cal.setLenient(false);
			dateFormat.setCalendar(cal);
			propertyValue = dateFormat.format(createDate);

		} catch ( ParseException e ) {

		}


		String caption = LocalizableString.sharedInstance().localizable("entity.ProjectItem.field.createDate");
		result = this.inputControl("createDate", caption, propertyValue, readOnly);
		return result;
	}



	private String projectReleaseCell ( ProjectItem projectItem,
	                                    boolean readOnly ) {

		String result = null;
		String propertyValue = null;
		if ( projectItem != null ) {
			Date releaseDate = projectItem.getReleaseDate();
			if ( releaseDate != null ) {

				try {
					DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
					Calendar cal = dateFormat.getCalendar();
					cal.setLenient(false);
					dateFormat.setCalendar(cal);
					propertyValue = dateFormat.format(releaseDate);

				} catch ( ParseException e ) {

				}
			}


		}
		String caption = LocalizableString.sharedInstance().localizable("entity.ProjectItem.field.releaseDate");
		result = this.inputControl("releaseDate", caption, propertyValue, readOnly);
		return result;
	}



	@Override
	public String tabsPanelStyleClassName () {

		return String.format("%s-tabview", "horizontal");
	}



	/**
	 * ICustomDatasource
	 * 
	 * 
	 */

	@Override
	public void reloadData () {

		this.taskAssigneePerformFetchItems();

		this.taskReporterPerformFetchItems();


		Integer result = null;
		try {
			result = Integer.parseInt(this.projectId);
		} catch ( NumberFormatException e ) {
			result = null;
		}



		this.projectItem = (ProjectItem) projectListLayer.objectByUNID(result, null, this);

	}



	@Override
	public void setCustomDatasourceDelegate ( ICustomDatasourceDelegate delegate ) {

	}



	/**
     *
     *
     *
     *
     */

	@Override
	public int tabSheetCellsCount () {

		return 3;
	}



	@Override
	public TabSheetItemCell tabSheetCellAtIndex ( int index ) {

		return null;
	}



	@Override
	public String descriptionData () {

		return "DATA of the desc";
	}

	private ProjectItem projectItem = null;
	private String      projectId   = null;



	public String getProjectId () {

		return projectId;
	}



	public void setProjectId ( String projectId ) {

		this.projectId = projectId;
	}



	@Override
	public int detailTableViewItemsCount ( String userInfo ) {

		int result = 0;
		if ( "BASE".equalsIgnoreCase(userInfo) ) {
			result = 2;
		} else if ( "PEOPLE".equalsIgnoreCase(userInfo) ) {
			result = 2;
		} else if ( "DATES".equalsIgnoreCase(userInfo) ) {
			result = 2;
		} else if ( "DESCRIPTION".equalsIgnoreCase(userInfo) ) {
			result = 1;
		} else {
			result = 0;
			assert (true);
		}
		return result;
	}



	private String projectDescriptionItemAtIndex ( int index ) {

		String result = null;
		switch ( index ) {
			case 0: {
				result = "<li class=\"property-item-right\"><div class=\"wrap\"> <strong class=\"name\">" + "Status</strong><span>"
				        + "Resolved</span></div></li>";
				break;
			}
			default: {
				break;
			}
		}
		return result;
	}



	private String projectBaseItemAtIndex ( int index ) {

		LocalizableString localizableString = LocalizableString.sharedInstance();
		String result = null;

		String style = null;
		String propertyValue = null;
		String data = null;
		boolean readOnly = this.isReadOnly();


		switch ( index ) {
			case 0: {
				style = "-single";
				if ( this.projectItem != null ) {
					propertyValue = this.projectItem.getName();
				}
				String caption = localizableString.localizable("entity.ProjectItem.field.name");
				data = this.inputControl("name", caption, propertyValue, readOnly);
				break;
			}
			case 1: {
				style = "-single";
				if ( this.projectItem != null ) {
					propertyValue = this.projectItem.getDescription();
				}
				String caption = localizableString.localizable("entity.ProjectItem.field.description");
				data = this.textAreaControl("description", caption, propertyValue, readOnly);
				break;
			}
			default: {
				break;
			}
		}
		result = String.format("<li class=\"property-item%s\"><div class=\"wrap\">%s</li>", style, data);
		return result;
	}



	private String projectDatesItemAtIndex ( int index ) {

		String result = null;
		String style = null;
		String data = null;
		boolean readOnly = this.isReadOnly();
		switch ( index ) {
			case 0: {
				style = "-single";
				data = this.projectCreatedCell(this.projectItem, readOnly);
				break;
			}
			case 1: {
				style = "-single";
				data = this.projectReleaseCell(this.projectItem, readOnly);
				break;
			}
			default: {
				break;
			}
		}
		result = String.format("<li class=\"property-item%s\"><div class=\"wrap\">%s</li>", style, data);
		return result;
	}



	private String projectPeopleItemAtIndex ( int index ) {

		String result = null;
		String style = null;
		String data = null;
		boolean readOnly = this.isReadOnly();

		switch ( index ) {
			case 0: {
				style = "-single";
				data = this.projectAssigneeCellProjectTask(this.projectItem, readOnly);
				break;
			}
			case 1: {
				style = "-single";
				data = this.projectReporterCellProjectTask(this.projectItem, readOnly);
				break;
			}
			default: {
				break;
			}
		}
		result = String.format("<li class=\"property-item%s\"><div class=\"wrap\">%s</li>", style, data);
		return result;
	}



	@Override
	public String detailTableViewItemAtIndex ( String userInfo,
	                                           int index ) {

		String result = null;

		if ( "BASE".equalsIgnoreCase(userInfo) ) {
			result = this.projectBaseItemAtIndex(index);
		} else if ( "PEOPLE".equalsIgnoreCase(userInfo) ) {
			result = this.projectPeopleItemAtIndex(index);
		} else if ( "DATES".equalsIgnoreCase(userInfo) ) {
			result = this.projectDatesItemAtIndex(index);
		} else if ( "DESCRIPTION".equalsIgnoreCase(userInfo) ) {
			result = this.projectDescriptionItemAtIndex(index);
		}
		return result;
	}



	private <T> void projectAssigneeResponseItems ( List <T> items ) {

		projectAssigneeDictionary = new KeyValueDictionary();
		projectAssigneeDictionary.put(null, "-");
		Iterator <T> iterator = items.iterator();
		while ( iterator.hasNext() ) {
			User assignee = (User) iterator.next();
			projectAssigneeDictionary.put(String.format("%d", assignee.getId()), assignee.getName());
		}

	}



	private <T> void projectReporterResponseItems ( List <T> items ) {

		projectReporterDictionary = new KeyValueDictionary();
		projectReporterDictionary.put(null, "-");
		Iterator <T> iterator = items.iterator();
		while ( iterator.hasNext() ) {
			User reporter = (User) iterator.next();
			projectReporterDictionary.put(String.format("%d", reporter.getId()), reporter.getName());
		}

	}



	private void taskAssigneePerformFetchItems () {

		taskAssigneeServiceLayer = new UserListLayer();
		taskAssigneeServiceLayer.setUserInfo(Integer.valueOf(taskAssigneeFetchRequestUserInfo));
		taskAssigneeServiceLayer.setLayerDelegate(this);
		taskAssigneeServiceLayer.performRequestWithFilter(null, null);

	}



	private void taskReporterPerformFetchItems () {

		taskReporterServiceLayer = new UserListLayer();
		taskReporterServiceLayer.setUserInfo(Integer.valueOf(taskReporterFetchRequestUserInfo));
		taskReporterServiceLayer.setLayerDelegate(this);
		taskReporterServiceLayer.performRequestWithFilter(null, null);

	}



	private String projectAssigneeCellProjectTask ( ProjectItem projectItem,
	                                                boolean readOnly ) {

		String result = null;
		KeyValue propertyValue = null;
		if ( projectItem != null ) {
			User assignee = projectItem.getAssignee();
			if ( assignee != null ) {
				String idValue = String.format("%d", assignee.getId());
				String name = assignee.getName();
				propertyValue = new KeyValue(idValue, name);
			}
		}
		LocalizableString localizableString = LocalizableString.sharedInstance();
		String caption = localizableString.localizable("entity.ProjectItem.field.assignee");
		result = this.selectControl("assignee", caption, propertyValue, projectAssigneeDictionary, readOnly);
		return result;
	}



	private String projectReporterCellProjectTask ( ProjectItem projectItem,
	                                                boolean readOnly ) {

		String result = null;
		KeyValue propertyValue = null;
		if ( projectItem != null ) {
			User reporter = projectItem.getReporter();
			if ( reporter != null ) {
				String id = String.format("%d", reporter.getId());
				String name = reporter.getName();
				propertyValue = new KeyValue(id, name);
			}
		}
		LocalizableString localizableString = LocalizableString.sharedInstance();
		String caption = localizableString.localizable("entity.ProjectItem.field.reporter");
		result = this.selectControl("reporter", caption, propertyValue, projectReporterDictionary, readOnly);
		return result;
	}

}
